public class test1 {
    public String reverseWords(String s) {
        StringBuilder sb = removeBlankSpace(s);
        reverseString(sb,0,sb.length()-1);
        sb = reverseWord(sb);
        return sb.toString();
    }
    private StringBuilder removeBlankSpace(String s){
        int start = 0,end = s.length()-1;
        while(s.charAt(start)==' '){
            start++;
        }
        while(s.charAt(end)==' '){
            end--;
        }
        StringBuilder sb = new StringBuilder();
        while(start<=end){
            if(s.charAt(start)!=' '||sb.charAt(sb.length()-1)!=' '){
                sb.append(s.charAt(start));
            }
            start++;
        }
        return sb;
    }
    private void reverseString(StringBuilder sb,int start,int end){
        while(start<=end){
            char tmp = sb.charAt(start);
            sb.setCharAt(start,sb.charAt(end));
            sb.setCharAt(end,tmp);
            start++;
            end--;
        }
    }
    private StringBuilder reverseWord(StringBuilder sb){
        int start = 0,end = 1;
        while(start<sb.length()){
            while(end<sb.length() && sb.charAt(end)!=' '){
                end++;
            }
            reverseString(sb,start,end-1);
            start = end+1;
            end = start+1;
        }
        return sb;
    }
}
